package meijuli.com.join51.business.setpaypwd

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import meijuli.com.join51.business.R
import meijuli.com.join51.business.SimpleTextWatch
import com.jhx.common.framework.QuickBaseFragment
import com.jhx.common.http.ApiManager
import com.jhx.common.http.HttpRequest
import com.jhx.common.http.HttpResponse
import com.jhx.common.http.ResponseCallback
import com.jhx.common.model.Event
import meijuli.com.join51.business.setpaypwd.PayPwdActivity.mEventMessage
import meijuli.com.join51.business.ui.widget.PwdEditText
import com.jhx.common.utils.DisplayUtil
import meijuli.com.join51.business.utils.StringUtil
import com.jhx.common.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_paypwd.*
import me.foji.anko.clear
import meijuli.com.join51.business.service.ApiService
import org.greenrobot.eventbus.EventBus
import retrofit2.Call

/**
 * 确认交易密码
 *
 * @author Jack 2018-01-26 15:53
 */
class ConfirmPwdFragment : QuickBaseFragment() {
    private var mCall: Call<HttpResponse<String>>? = null
    private var mConfirmPwd: String? = null
    private var mPwd: String? = null
    private var mCode: String? = null
    private var mPhone: String? = null

    companion object {
        val KEY_PWD = "pay_pwd"
    }

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.activity_paypwd, container, false)
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        text_message.text = "确认交易密码"
        mPwd = arguments?.getString(KEY_PWD)
        mPhone = arguments?.getString(PayPwdActivity.KEY_PHONE)
        mCode = arguments?.getString(PayPwdActivity.KEY_CODE)
        pwdEditText.addTextChangedListener(object : SimpleTextWatch() {
            override fun afterTextChanged(editable: Editable) {
                text_confirm.isEnabled = pwdEditText.text.length >= 6
            }
        })

        pwdEditText.setOnInputListener(object : PwdEditText.OnInputListener {
            override fun onInput(text: CharSequence) {

            }

            override fun onInputFinish(text: CharSequence) {
                mConfirmPwd = text.toString()
            }
        })

        text_confirm.setOnClickListener{
            if(mPwd != mConfirmPwd) {
                ToastUtil.getInstance().showToast(activity, "交易密码不一致，请重新输入")
                pwdEditText.clear()
                pop()
                return@setOnClickListener
            }
            setPayPwd()
        }

        showKeyboard(pwdEditText)
        val params = text_confirm.layoutParams as LinearLayout.LayoutParams
        params.width = DisplayUtil.dip2px(activity, 50f) * 6
        text_confirm.layoutParams = params
    }



    private fun setPayPwd() {
        showLoadingDialog()
        mCall = ApiManager.get().getApiService(ApiService::class.java).setOrUpdatePwd(
                StringUtil.encodeToSHA256(mConfirmPwd),
                mPhone,
                mCode)
        HttpRequest.getRequest().autoRecycle(activity).start(mCall, object: ResponseCallback<String>() {
            override fun onSuccess(url: String?, data: String?) {
                hideLoadingDialog()
                val dialog = Dialog(activity)
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
                dialog.setContentView(R.layout.dialog_complete)
                dialog.show()
                val event = Event()
                event.message = mEventMessage
                EventBus.getDefault().post(event)
                Handler().postDelayed({
                    dialog.dismiss()
                    activity?.finish()
                }, 3000)
            }

            override fun onError(url: String?, errorCode: Int, errorMsg: String?) {
                super.onError(url, errorCode, errorMsg)
                hideLoadingDialog()
            }
        })
    }

    private fun showKeyboard(editText: EditText) {
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED)
    }
}